package com.popo.android.lockscreen.impl.httptool;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;


import net.sf.json.JSONArray;

import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.json.JSONException;
import org.json.JSONObject;


/**
 * 使用apache工具实现的登录类
 * 
 * @author Administrator
 * 
 */
public class ApacheHttpClientTool  {

	boolean isError = false;
	String ErrorMessage;

	public ApacheHttpClientTool() {
//		responseHeader = new ContentValues();
	}

	

	public InputStream doPost(String url, String data, File[] files)
			throws Exception {
		// TODO Auto-generated method stub
		org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
		PostMethod postMethod = new PostMethod(url);
//		postMethod.addRequestHeader("enctype", "multipart/form-data");
		Part[] part = null;
		int partNumbers = 0;
		if (data != null)
			partNumbers ++;
		if (files != null)
			partNumbers += files.length;

		if (partNumbers > 0)
			part = new Part[partNumbers];
		
		int partkey = 0;
		
		if(data!=null){
			part[partkey++]=new StringPart("json", data, "UTF-8");
		}
	
		// 填充附件
		if (files != null) {
			System.out.println("files in not null");
			int length = files.length;
			for (int i = 0; i < length; i++) {
				try {
					System.out.println(files[i].getName());
					part[partkey++] = new FilePart(files[i].getName(), files[i]);
				} catch (FileNotFoundException ex) {
					throw (ex);
				}
			}
		}

		httpClient.getParams().setContentCharset("UTF-8");
		
		/**
		 * part如果有空的话会报错处理下吧
		 */
		MultipartRequestEntity mrp = null;
		if (part !=null && partkey < part.length) {

			Part[] part2 = new Part[partkey];
			for (int i = 0; i < partkey; i++) {
				part2[i] = part[i];
			}
			mrp = new MultipartRequestEntity(part2, postMethod.getParams());
		} else {
			mrp = new MultipartRequestEntity(part, postMethod.getParams());
		}
		postMethod.setRequestEntity(mrp);
		httpClient.executeMethod(postMethod);
		part = null;
		return postMethod.getResponseBodyAsStream();
	}

	public String doPostResponseMessage(String url, String data, File[] files)
			throws Exception {
		// TODO Auto-generated method stub
		InputStream inputStream = doPost(url, data, files);
		StringBuilder stringBuilder = new StringBuilder();
		try {

			byte[] buffer = new byte[1024 * 8];
			BufferedInputStream bufferedInputStream = new BufferedInputStream(
					inputStream);
			
			
			while (bufferedInputStream.read(buffer) != -1) {
				stringBuilder.append("");
			}
			buffer = null;
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw (e);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw (e);
		} finally {
			try {
				inputStream.close();
			} catch (Exception e) {
				// TODO: handle exception
				throw (e);
			}
		}
		return stringBuilder.toString();
	}

	public static void main(String[] args) {
		ApacheHttpClientTool apacheHttpClientTool = new ApacheHttpClientTool();
		String s=null;
//		File f = new File("165247.txt");
//		File[] fs=null;
//		if(f.exists()){
//			fs = new File[]{f};
//			System.out.println("f exists");
//		}
		
		HashMap<String, Integer[]> map = new HashMap<String, Integer[]>();
		map.put("1", new Integer[]{2,3,5,6});
		map.put("12", new Integer[]{24,33,35,36});
		
		
		try {
			s = apacheHttpClientTool.doPostResponseMessage("http://localhost/", "sadfasssfas", null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(s);
		
		StringBuilder json = new StringBuilder("{\"zushou365\":\"{\\\"tableSet\\\":{\\\"list\\\":[");
		
		Set<String> keys = map.keySet();
		Iterator<String > keyIterator =keys.iterator();
		while(keyIterator.hasNext()){
			String houseId = keyIterator.next();
			StringBuilder house = new StringBuilder("{\\\""+houseId+"\\\":"+houseId+",\\\"webList\\\":[");
			Integer[] webs = map.get(houseId);
			int length = webs.length;
			for(int i =0;i<length;i++){
				house.append(webs[i]);
				if(i<length-1){
					house.append(",");
				}
			}
			house.append("]}");
			json.append(house);
			if(keyIterator.hasNext()){
				json.append(",");
			}
			
		}
		
		
		json.append("]}}\"}");
		
		System.out.println(json);
		
		try {
			JSONObject o = new JSONObject(json.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
